package admin

import (
	"fmt"
	"yunj/config"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/controller"
	"yunj/pkg/yunj/app/service"
	"yunj/pkg/yunj/app/service/admin/authservice"
	yunjConfig "yunj/pkg/yunj/config"
	"yunj/pkg/yunj/core/builder"
	"yunj/pkg/yunj/core/consts"
	"yunj/pkg/yunj/core/response"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
)

type Controller struct {
	controller.Controller
}

// 模板渲染
// @Param  path  string  模板路径
// @Param  data  map[string]any|struct  渲染数据
func (ctrl *Controller) Render(ctx *gin.Context, path string, data ...any) {
	// 设置公共参数
	ctrl.SetCommonData(ctx)
	// 处理传入参数
	if len(data) > 0 {
		ctrl.Assign(data[0])
	}
	// 模板渲染
	response.Render(ctx, "admin/"+path, ctrl.Data)
}

// 设置公共参数
func (ctrl *Controller) SetCommonData(ctx *gin.Context) {
	// layui固定扩展
	response.SetCtxRenderLayModuleExtends(ctx, util.MapMerge(yunjConfig.LayModuleExtends, config.LayModuleExtends))
	breadcrumbHtml, err := authservice.Auth.GetBreadcrumbHtml(ctx)
	if err != nil {
		fmt.Printf("获取面包屑失败！%v\r\n", err)
	}
	ctrl.Assign(map[string]any{
		"version":          config.VERSION,
		"layuiVersion":     yunjConfig.LayuiVersion,
		"appName":          global.Config.App.Name,
		"favicon":          service.SettingValue("sys", "favicon", "/favicon.ico"),
		"keywords":         service.SettingValue("sys", "keywords", ""),
		"description":      service.SettingValue("sys", "description", ""),
		"yunjStaticPrefix": consts.YUNJ_STATIC_PREFIX,
		"styleFileList":    global.Config.App.Admin.StyleFileList,
		"exposeConfig":     global.ExposeConfig,
		"themeConfig":      global.ThemeConfig,
		"breadcrumbHtml":   breadcrumbHtml,
	})
}

// 构建器渲染
func (ctrl *Controller) RenderBuilder(ctx *gin.Context, b builder.BuilderInterface, path string, data ...map[string]any) {
	b.Assign()
	if ctx.IsAborted() {
		return
	}
	// 创建一个新的 map[string]any 并合并数据
	newData := map[string]any{}
	if len(data) > 0 {
		for k, v := range data[0] {
			newData[k] = v
		}
	}
	builderId, _ := b.GetId()
	newData["builderId"] = builderId
	ctrl.Render(ctx, path, newData)
}

// 表单构建器渲染
func (ctrl *Controller) RenderForm(ctx *gin.Context, f *builder.Form, data ...map[string]any) {
	ctrl.RenderBuilder(ctx, f, "template/form", data...)
}

// 表格构建器渲染
func (ctrl *Controller) RenderTable(ctx *gin.Context, t *builder.Table, data ...map[string]any) {
	ctrl.RenderBuilder(ctx, t, "template/table", data...)
}

// 导入构建器渲染
func (ctrl *Controller) RenderImport(ctx *gin.Context, i *builder.Import, data ...map[string]any) {
	ctrl.RenderBuilder(ctx, i, "template/import", data...)
}
